package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.article.IArticleClient;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.common.constants.user.UserConstants;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @Author ZhangXiXi
 * @Description TODO
 * @date 2021/2/20 11:19
 * @Version 1.0
 */
@Service
@Slf4j
@Transactional
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //1 检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 分页检查
        dto.checkParam();
        //  根据状态精确查询
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> queryWrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {
            queryWrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        //分页条件构建
        page = page(page, queryWrapper);
        //返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getRecords());
        return pageResponseResult;
    }

    @Override
    @GlobalTransactional
    public ResponseResult updateStatus(AuthDto dto, Short status) {
        //1 检查参数
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 修改认证信息
        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);
        //3 如果审核状态是9 需要创建自媒体账户和作者信息
        if (status.equals(UserConstants.PASS_AUTH)) {
            ResponseResult responseResult = createWmUserAndAuthor(dto);
            if (responseResult != null) {
                return responseResult;
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    private IWemediaClient wemediaClient;
    @Autowired
    private ApUserMapper apUserMapper;

    /**
     * @Description:创建自媒体账户和作者
     * @Parameter:
     * @Return:
     **/
    private ResponseResult createWmUserAndAuthor(AuthDto dto) {
        Integer userRealnameId = dto.getId();
        /**
         *@Description:查询用户认证信息
         *@Parameter:
         *@Return:
         **/
        ApUserRealname apUserRealname = getById(userRealnameId);
        if (apUserRealname == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        /**
         *@Description:查询app端用户信息
         *@Parameter:
         *@Return:
         **/
        Integer userId = apUserRealname.getUserId();
        ApUser apUser = apUserMapper.selectById(userId);
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //创建自媒体账户
        WmUser wmUser = wemediaClient.findWmUserByName(apUser.getName());
        if (wmUser == null) {
            wmUser = new WmUser();
            wmUser.setApAuthorId(5);
            wmUser.setApUserId(apUser.getId());
            wmUser.setName(apUser.getName());
            wmUser.setCreatedTime(new Date());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setStatus(9);
            wemediaClient.save(wmUser);
        }
        //创建作者
        createApAuthor(wmUser);
        apUser.setFlag((short) 1);
        apUserMapper.updateById(apUser);
        return null;
    }

    @Autowired
    private IArticleClient articleClient;

    private void createApAuthor(WmUser wmUser) {
        ApAuthor apAuthor = articleClient.findByUserId(wmUser.getApUserId());
        if (apAuthor == null) {
            apAuthor = new ApAuthor();
            apAuthor.setUserId(wmUser.getApUserId());
            apAuthor.setType(2);
            apAuthor.setName(wmUser.getName());
            apAuthor.setCreatedTime(wmUser.getCreatedTime());
            apAuthor.setWmUserId(wmUser.getId());
            articleClient.save(apAuthor);
        }
    }
}
